package com.ssj.ssj.modules.man.service;

import com.ssj.ssj.exception.BusinessException;
import com.ssj.ssj.modules.security.context.AuthenticationContextHolder;
import com.ssj.ssj.modules.security.services.AccountUser;
import com.ssj.ssj.modules.security.services.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class LoginService {

  @Autowired
  TokenService tokenService;

  @Autowired
  private AuthenticationManager authenticationManager;

  public String login(String username, String password, String code, String uuid) {

    // 验证码校验
    validateCaptcha(username, code, uuid);
    // 登录前置校验
    loginPreCheck(username, password);
    // 用户验证
    Authentication authentication = null;
    try {
      UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
      AuthenticationContextHolder.setContext(authenticationToken);
      // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
      authentication = authenticationManager.authenticate(authenticationToken);
    } catch (Exception e) {
      if (e instanceof BadCredentialsException) {
        throw new BusinessException("user.password.not.match",e);
      }
      else {
        throw new BusinessException(e.getMessage());
      }
    } finally {
      AuthenticationContextHolder.clearContext();
    }
    AccountUser loginUser = (AccountUser) authentication.getPrincipal();
    recordLoginInfo(loginUser.getId());
    // 生成token
    return tokenService.createToken(loginUser);
  }

  /**
   * checker
   * @param username
   * @param password
   */
  private void loginPreCheck(String username, String password) {

  }

  /**
   * 验证码校验
   * @param username
   * @param code
   * @param uuid
   */
  private void validateCaptcha(String username, String code, String uuid) {

  }

  /**
   * 记录登录信息
   *
   * @param userId 用户ID
   */
  public void recordLoginInfo(Integer userId) {
    log.info("登陆的用户ID是{}", userId);
  }

}
